//
//  FR_HomeViewController.m
//  FaceRecognition
//
//  Created by Sylar on 2016/11/28.
//  Copyright © 2016年 Sylar. All rights reserved.
/*
    02.09  增加员工管理
 
 1.老师--底片--班级列表--学生----家长列表（新界面）。--修改家长信息（底片，姓名，身份）、
 
 2.老师--底片--班级列表--学生---搜索学生结果，点击进入--修改家长信息（底片，姓名，身份）、
 
 3.家长--底片--学生列表--家长列表，--查看该学生下所有家长信息（新界面）。
 */

#import "FR_ManagerInfoViewController.h"

#import "StudentListViewController.h"
#import "ManagerInfoModel.h" //请求结果模型类，信息管理统一使用
#import "ClassListCell.h"
#import "StudentListTableViewCell.h"

#import "Students.h" //学生模型
#import "UploadPhotoViewController.h"
#import "ParentPhotoListViewController.h"
#import "YiTuUploadPhotoViewController.h"

@interface FR_ManagerInfoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;

/**老师身份所管理班级数组*/
@property (nonatomic,strong) NSMutableArray *dataArr;

/**家长身份下所管理的学生数组*/
@property (nonatomic,strong) NSMutableArray *studentsArr;

/**登录身份 1..老师; 2..家长*/
@property (nonatomic,assign) int lastType;

/**记录上一次身份，与新的身份判断，不一样就从新加载数据*/
@property (nonatomic,assign) int tmpType;

@property (nonatomic,strong) UILabel *nohisLabel;

/**是否是学校管理员*/
@property (nonatomic,assign) NSInteger schollManagerNum;

/**是否是班主任,教室里面没学生等同于没班主任*/
@property (nonatomic,assign) int classesHasNoStudents;


@end

@implementation FR_ManagerInfoViewController

#pragma mark -Getter
- (UITableView *)tableView{
    
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, SCREENHEIGH - SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#f5f8fa"];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        UIView *v = [[UIView alloc] init];
        v.backgroundColor = [UIColor colorWithHexString:@"#f5f8fa"];
        _tableView.tableFooterView = v;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            if (_lastType == 1) {
                
                [self getManageClasses];
            }else{
                
                [self getAllChildrens];
            }
        }];
        
        
        self.nohisLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 150, SCREENWIDTH, 15)];
        [self.nohisLabel setFont:[UIFont systemFontOfSize:14]];
        [self.nohisLabel setText:@"当前暂无班级"];
        [self.nohisLabel setTextColor:[UIColor colorWithHexString:@"#979797"]];
        self.nohisLabel.textAlignment = NSTextAlignmentCenter;
        self.nohisLabel.hidden = YES;
        
        [_tableView addSubview:self.nohisLabel];
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArr{
    
    if (_dataArr == nil) {
        
        _dataArr = [NSMutableArray array];
    }
    
    return _dataArr;
}

- (NSMutableArray *)studentsArr{
    
    if (_studentsArr == nil) {
        
        _studentsArr = [NSMutableArray array];
    }
    
    return _studentsArr;
}

#pragma mark -LifeCycle
- (id)init
{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = NO;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f5f8fa"];
    self.title = @"底片";

    //去掉导航条背景颜色的透明度
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.hidesBottomBarWhenPushed = YES;
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = left;
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.schollManagerNum = [SYAccountTool ShareAccount].account.schoolManage;
    
    self.lastType = [SYAccountTool ShareAccount].account.lasttype;
    
    if (self.lastType == 2) {
        
        self.nohisLabel.hidden = YES;
    }
    
    if (self.lastType != _tmpType) {
        
        _tmpType = self.lastType;
        
        if (self.lastType == 1) {
            //获取用户班主任身份下班级
            [self getManageClasses];
        }else{
            //获取家长身份下的孩子
            [self getAllChildrens];
            
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
}

- (void)back {
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.15;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromLeft;
    [self.view.window.layer addAnimation:animation forKey:nil];
    
    [self.navigationController dismissViewControllerAnimated:NO completion:NULL];
}

#pragma mark -UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.lastType == 1 ) { //有管理员身份
        
        
        
        if (self.schollManagerNum){
            
            return 3 ;
        }
        
        return 2;
        
    }
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.lastType == 1) {
        
        if (section == 0) return self.dataArr.count;
        
        if (section == 1 || section == 2) return 1;
        
    }
    
    return self.studentsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellId = @"cellid";
    
    if (self.lastType == 1) { //老师身份
        
        ClassListCell *cell = [[ClassListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        if (indexPath.section == 0) { //班级列表
            
            ManagerInfoModel *model = [self.dataArr objectAtIndex:indexPath.row];
            if (indexPath.row == self.dataArr.count - 1) { //每个section中最后一个cell隐藏底部的线
                
                cell.lineView.hidden = YES;
            }
            cell.label.text = model.classname;

        }else if (indexPath.section == 1){
            
            if (_schollManagerNum) { //员工
                
                cell.label.text = @"员工管理";
                cell.lineView.hidden = YES;
            }else{
                
                cell.label.text = @"个人管理";
                cell.lineView.hidden = YES;
            }
    
        }else if (indexPath.section == 2){
            
            cell.label.text = @"个人管理";
            cell.lineView.hidden = YES;
        }
        
        return cell;
        
    }else if (self.lastType == 2){
        
        StudentListTableViewCell *cell = [[StudentListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        ManagerInfoModel *model = [self.studentsArr objectAtIndex:indexPath.row];
        cell.childModel = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0 && _lastType == 1 && _classesHasNoStudents == 1) {
        
        return 0; //班里没人
        
    }else{
    
        return 10;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 10)];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

#pragma mark -UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ManagerInfoModel *model;
   
    NSString * facetype = [SYAccountTool ShareAccount].account.facetype;
   
    if (self.lastType == 1) {
        
        StudentListViewController *stuVC;
        
        if (indexPath.section == 0) {
            
            stuVC = [[StudentListViewController alloc] init];
            stuVC.hidesBottomBarWhenPushed = YES;
            
            model = [self.dataArr objectAtIndex:indexPath.row];
            
            stuVC.classid = model.classid;
            stuVC.title = model.classname;
            stuVC.manageType = 0; //班主任查看学生列表
            [self.navigationController pushViewController:stuVC animated:YES];
            
        }else if (indexPath.section == 1){
            
            if (_schollManagerNum) { //选择员工
                
                stuVC = [[StudentListViewController alloc] init];
                stuVC.hidesBottomBarWhenPushed = YES;

                stuVC.scid = [NSString stringWithFormat:@"%ld",(long)_schollManagerNum];
                stuVC.manageType = 1; //管理员查看员工列表
                
                [self.navigationController pushViewController:stuVC animated:YES];
                
            }else{  //选择个人
                
                //普通老师查看个人
                [self selectPersonalVC:3];
                
            }
            
        }else if (indexPath.section == 2){ //管理员身份  选择个人
            
            [self selectPersonalVC:4];
        }
        
        
    }else if (self.lastType == 2){
      //没有涉及到旷世和依图的接口
        model = [self.studentsArr objectAtIndex:indexPath.row];
        ParentPhotoListViewController *uploadVC = [[ParentPhotoListViewController alloc] init];
        uploadVC.model = model;
        uploadVC.lastType = _lastType;
        
        [self.navigationController pushViewController:uploadVC animated:YES];
    }
}

//选择个人
- (void)selectPersonalVC:(int)manageType{
    
    ManagerInfoModel *model = [ManagerInfoModel loginUserAccount];
   NSString * facetype = [SYAccountTool ShareAccount].account.facetype;
   
   if ([facetype isEqualToString:@"0"]) {
      
       UploadPhotoViewController *uploadVC = [[UploadPhotoViewController alloc] init];
       uploadVC.manageType = manageType;
       uploadVC.lastType = _lastType;
       uploadVC.model = model;
      
       [self.navigationController pushViewController:uploadVC animated:YES];
      
   }else
   {
      YiTuUploadPhotoViewController *uploadVC = [[YiTuUploadPhotoViewController alloc] init];
      uploadVC.manageType = manageType;
      uploadVC.lastType = _lastType;
      uploadVC.model = model;
      
      [self.navigationController pushViewController:uploadVC animated:YES];
   }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return self.lastType == 1 ? 45 : 57;
}

#pragma mark -Private
#pragma makr -Request
//获取老师身份下所有管理班级(作为班主任的班级)
- (void)getManageClasses{
    
    NSMutableDictionary * paramDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [paramDic setObject:USERID forKey:@"teacherid"];
    [paramDic setObject:SCHOOLID forKey:@"scid"];
    [paramDic setObject:[SYAccountTool ShareAccount].account.schoolManage > 0?@"1":@"0" forKey:@"type"];
    
    __weak typeof(self) weakSelf = self;
    
    [Utils Java_get:@"api/getTeacherClass" parameters:paramDic success:^(NSInteger recode, id jsonObject) {
        
        NSArray *array = [jsonObject objectForKey:@"re_data"];
        
        [self.dataArr removeAllObjects];
        
        if (array.count == 0) {
            
            /*  去掉当前暂无班级的提示
            if (self.schollManagerNum > 0) { //管理员身份
                
                self.nohisLabel.hidden = YES;
            }else{
                self.nohisLabel.hidden = NO;
            }
            */
            
            weakSelf.classesHasNoStudents = 1;
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
            return;
        }
        
        self.nohisLabel.hidden = YES;
        
        weakSelf.classesHasNoStudents = 0;
        
        self.dataArr = [ManagerInfoModel mj_objectArrayWithKeyValuesArray:array];
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSInteger recode, NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        [self showHint:error.localizedDescription];
    }];
    /*
    RequestParam *param = [[RequestParam alloc] init];
    param.method = @"sy_rollcall_classlist";
    param.pageno = @"1";
    param.pagesize  = @"10000";
    param.teacherid = USERID;
    
    __weak typeof(self) weakSelf = self;
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *array = [jsonObject objectForKey:@"re_data"];
        
        [self.dataArr removeAllObjects];
        
        if (array.count == 0) {
            
            if (self.schollManagerNum > 0) { //管理员身份
                
                self.nohisLabel.hidden = YES;
            }else{
                self.nohisLabel.hidden = NO;
            }
            
            weakSelf.classesHasNoStudents = 1;
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
            return;
        }
        
        self.nohisLabel.hidden = YES;
        
        weakSelf.classesHasNoStudents = 0;
        
        self.dataArr = [ManagerInfoModel mj_objectArrayWithKeyValuesArray:array];
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        [self showHint:error.localizedDescription];
    }];
     */
}

//获取家长身份下所有学生()
- (void)getAllChildrens{
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:USERID forKey:@"parentid"];
    
    [Utils Java_get:@"api/getChildClass" parameters:dict success:^(NSInteger recode, id jsonObject) {

        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        self.studentsArr = [ManagerInfoModel mj_objectArrayWithKeyValuesArray:arr];
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    }failure:^(NSInteger recode, NSError *error) {
        [self showHint:error.localizedDescription];
    }];
    
}


@end
